/**  定义Admin相关的接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response.js");
const changeTree = require("../changeTree");
const md5 = require("md5");

// 引入mysql连接池
const pool = require("../utils/db.js");

const jwt = require("jsonwebtoken");
const { error } = require("../utils/Response.js");
const SECRET_KEY = "JWT_SECRET_KEY";

/**
 * 处理登录业务
 */
router.post("/user-login", (req, resp) => {
  let { role_username, role_password } = req.body;
  // 表单验证
  let schema = Joi.object({
    role_username: Joi.string().required().pattern(new RegExp("^\\w{3,15}$")), // 必填
    role_password: Joi.string().required().pattern(new RegExp("^\\w{6,15}$")), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 查询数据库，账号密码是否填写正确
  let sql =
    "select * from role where role_username = ? and role_password=MD5( ? ) ";
  pool.query(sql, [role_username, role_password], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      resp.send(Response.error(1001, "账号密码输入错误"));
    } else {
      // 获取登录用户对象
      let user = result[0];
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      let payload = { id: user.id, nickname: user.role_nickname };
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: "1d" });
      // 返回user对象与token字符串
      user.role_password = undefined;
      resp.send(Response.ok({ user, token }));
    }
  });
});

// 权限管理 返回给前端此角色拥有的权限
router.post("/rights", async (req, resp) => {
  let { role_id, user_id } = req.body;
  try {
    let sql =
      "select * from role where id in (select role_id from role_user where user_id=?)";
    let result = await pool.querySync(sql, [user_id]);

    let sql2 =
      "select * from menu where m_id in (select menu_id from role_menu where role_id=?)";
    let result2 = changeTree(await pool.querySync(sql2, [role_id]), 0, 0);
    resp.send(Response.ok({ result, result2 }));
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 杨绍平开始
// 用户注册
router.post("/register", (req, res) => {
  let { u_id, u_phone, u_pwd, u_card, u_name } = req.body;
  let sql =
    "insert into register (u_id, u_phone, u_pwd, u_card,u_name) values (?,?,MD5(?),?,?)";
  pool.query(sql, [u_id, u_phone, u_pwd, u_card, u_name], (err, result) => {
    if (err) {
      res.send(Response.error(500, err));
      throw err;
    }
    // 将结果返回给客户端
    res.send(Response.ok(result));
  });
});

// 用户登录
router.post("/user/Mylogin", (req, res) => {
  let { u_phone, u_pwd, u_id } = req.body;
  let sql = "select * from register where u_phone=? and u_pwd=MD5(?)";
  console.log(u_phone, u_pwd);
  pool.query(sql, [u_phone, u_pwd, u_id], (err, result) => {
    if (err) {
      res.send(Response.error(500, error));
      throw err;
    } // 将结果返回给客户端
    res.send(Response.ok(result));
    console.log(result);
  });
});

// 用户修改信息
router.post("/user/update", (req, res) => {
  let { u_id, u_phone, u_card, u_name } = req.body;
  let sql =
    "update register set u_phone=?,u_card=?,u_name=? where u_id=?";
  pool.query(sql, [u_phone, u_card, u_name, u_id], (err, result) => {
    if (err) {
      res.send(Response.error(500, error));
      throw err;
    }
    // 将结果返回给客户端
    res.send(Response.ok(result));
  });
});

// 根据用户id查询个人信息
router.post("/user/from", (req, res) => {
  let { u_id } = req.body;
  let sql = "select * from register where u_id=?";
  pool.query(sql, [u_id], (err, result) => {
    if (err) {
      res.send(Response.error(500, error));
      throw err;
    }
    // 将结果返回给客户端
    res.send(Response.ok(result));
  });
});
// 杨绍平结束

// 将router对象导出
module.exports = router;
